<template>
  <el-container>
    <el-main>
  <div style="width: 650px;text-align:center;margin: 5px auto;background:#409EFF; color:#FFF">
    <h1 style="margin-bottom: 40px;">{{ msg }}</h1>
  <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
    <el-row>
      <el-col :span="23">
    <el-form-item label="用户名" prop="userName">
      <el-input type="text" v-model="ruleForm.userName" autocomplete="off" ></el-input>
    </el-form-item>
      </el-col>
     </el-row>
    <el-row>
      <el-col :span="23">
    <el-form-item label="密码" prop="pass">
      <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
    </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="23">
    <el-form-item label="验证码" prop="verificationCode">

       <div class="captcha_code">
      <el-input v-model="ruleForm.verificationCode" style="width: 73%;text-align:left;" @keyup.native="autoSubmit($event)"></el-input>
      <img src="" ref="code" @click="changeCode">
       </div>
    </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="23">
    <el-form-item >
      <div >
        <el-button  @click="submitForm('ruleForm')">登录</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
        <el-button @click="register()">注册</el-button>
        <el-button @click="forgetPassword()">忘记密码</el-button>
      </div>
    </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  </div>
    </el-main>
    <el-footer>
      <el-row :gutter="20">
        <el-col :span="24"><div class="jz"><a href="https://beian.miit.gov.cn">京ICP备20022306号-2</a></div></el-col>
      </el-row>
    </el-footer>
  </el-container>
</template>

<script>
import request from "../utils/request";
import {baseUrl} from "../utils/env";

export default {
  name: "Login",
  data () {
    const validateUser = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    const validateVerificationCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    return {
      msg: '欢迎使用AutoScript代码生成',
      ruleForm: {
        userName: '',
        pass: '',
        verificationCode: ''
      },

      rules: {
        userName: [{ required: true,validator: validateUser, trigger: "blur" }],
        pass: [{ required: true,validator: validatePass, trigger: "blur" }],
        verificationCode: [{ required: true,validator: validateVerificationCode, trigger: "blur" }]
      }

    }
  },
  methods:{
    autoSubmit:function (ev){
      //debugger;
      if(ev.code === "Enter") {
        this.submitForm('ruleForm');
      }
    },
    submitForm(formName) {
      let _this = this;
      const  param = {
        userName: _this.ruleForm.userName,
        passWord: _this.ruleForm.pass,
        verificationCode: _this.ruleForm.verificationCode
      };
      this.$refs[formName].validate(valid => {
        if (valid) {
          request({
            method: "POST",
            url: "/api/User/login",
            data: param
          })
            .then(res => {
              if (res.data.status=="1") {
                localStorage.setItem("islogin", 1);
                localStorage.appToken = res.data.appToken;
                localStorage.userName = res.data.userName;
                localStorage.userId = res.data.userId;
                console.log(localStorage.getItem("islogin"));
                _this.$router.push({ path: "/main" });
              } else {
                this.$alert(res.data.message, {
                  confirmButtonText: '确定',
                  callback: action => {
                  }
                });
                return false;
              }
            })
            .catch(err => {
              debugger;
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    register(){
      this.$router.push({ path: "/userRegister" });
    },
    forgetPassword(){
      this.$router.push({ path: "/forgetPassword" });
    },
    async changeCode() {
      let that = this;
      await request({
        method: "POST",
        url: "/api/User/makeNewSession"
      })
        .then(res => {
          if (res.data.status == "1") {
            localStorage.sessionId = res.data.sessionId;
            let captchaKey = Math.random()
              .toString(36)
              .substring(2);
            that.$refs.code.setAttribute(
              "src",
              baseUrl +
              "/api/User/getVerifyCode?captcha_key=" + captchaKey+"&sessionId="+res.data.sessionId
            );
          } else {
            console.log('获取新session失败!');
            return false;
          }
        })
        .catch(err => {
          debugger;
          console.log(err);
        });

    }

  },
  mounted() {
    this.changeCode();
  }
}

</script>

<style scoped>
.jz{ margin:0 auto; width:320px; height:20px;text-align:center; border:0px solid #F00}

</style>
